import Component from '@teld/q-components/Carousel';
import useMappingProps from 't/common/hooks/useMappingProps';
import {
  commonProps,
  fixNameSpace,
  pickOwnForBasicComponent,
} from 't/common/utils';
import { defineComponent, ref, watch, onMounted } from 'vue';
import CarouselSlide from './CarouselSlide';
import styles from './index.module.scss';
import './index.scss';

export default defineComponent({
  name: fixNameSpace(Component.name),
  props: {
    ...commonProps,
    ...Component.props,
    listDataSource: {
      type: Array,
      default() {
        return [];
      },
    },
    modelValue: {
      type: [String, Boolean, Number],
      default() {
        return 0;
      },
    },
    animated: {
      type: [String, Boolean],
      default() {
        return true;
      },
    },
    arrows: {
      type: Boolean,
      default() {
        return true;
      },
    },
    urlField: {
      type: String,
      default() {
        return 'Url';
      },
    },
    noDataText: {
      type: String,
      default() {
        return '无数据';
      },
    },
    swipeable: {
      type: Boolean,
      default() {
        return true;
      },
    },
    transitionNext: {
      type: String,
      default() {
        return 'slide-left';
      },
    },
    transitionPrev: {
      type: String,
      default() {
        return 'slide-right';
      },
    },
    autoPlayModel: {
      type: Boolean,
      default() {
        return false;
      },
    },
    imgSize: {
      type: String,
      default() {
        return '';
      },
    },
    coverType: {
      type: String,
      default() {
        return '';
      },
    },
    containType: {
      type: String,
      default() {
        return '';
      },
    },
  },
  emits: [],

  setup(props, { attrs, emit, expose, slots }) {
    const refComponent = ref();
    const [mappingProps, mappingExpose] = useMappingProps(props);
    const { default: defaultSlot } = slots;
    let initAutoPlay = mappingProps.autoplay;

    expose(mappingExpose);
    console.log(slots, 'carousel');
    if (!mappingProps.autoPlayModel) {
      mappingProps.autoplay = 0;
    }
    let imgSizeClass = ref('');
    if (mappingProps.imgSize == 'cover' && mappingProps.coverType) {
      imgSizeClass = `t-carousel-imgsize-${mappingProps.imgSize}-${mappingProps.coverType}`;
    }
    if (mappingProps.imgSize == 'contain' && mappingProps.containType) {
      imgSizeClass = `t-carousel-imgsize-${mappingProps.imgSize}-${mappingProps.containType}`;
    }
    onMounted(() => {
      let control = document.querySelectorAll(
        '.t-carousel .q-carousel__navigation-inner .q-btn',
      );
      let arr = document.querySelectorAll(
        '.t-carousel .q-carousel__arrow .q-btn',
      );
      const nodes = Array.from(control);
      nodes.forEach(node => {
        node.setAttribute('tabIndex', 1);
      });
      const arrs = Array.from(arr);
      arrs.forEach(node => {
        node.setAttribute('tabIndex', 1);
      });
    });
    watch(
      () => {
        return [mappingProps.autoPlayModel, mappingProps.autoplay];
      },
      (newVal, oldVal) => {
        if (newVal[1] != oldVal[1]) {
          initAutoPlay = newVal[1];
        }
        if (!mappingProps.autoPlayModel) {
          mappingProps.autoplay = 0;
        } else {
          mappingProps.autoplay = initAutoPlay;
        }
      },
    );
    let isCarouselFocus = false;
    function carouselFocus() {
      isCarouselFocus = true;
    }
    function carouseKeydown(event) {
      if (!isCarouselFocus) {
        return;
      }
      var keyCode = event.keyCode || event.which;
      console.log(keyCode);
      // 左键：37，右键：39
      if (keyCode === 37 && event.shiftKey === false) {
        // 左键
        // 阻止默认行为，例如浏览器可能的滚动
        event.preventDefault();
        refComponent.value.previous();
      } else if (keyCode === 39 && event.shiftKey === false) {
        // 右键
        event.preventDefault();
        refComponent.value.next();
      }
    }
    // defaultSlot?.() ??
    return () => {
      return (
        <Component
          ref={refComponent}
          {...attrs}
          {...pickOwnForBasicComponent(mappingProps, Component.props, attrs)}
          class={['t-carousel', 'no-outline', styles.module, imgSizeClass]}
          v-show={mappingProps.visible}
          onFocus={carouselFocus}
          onKeydown={carouseKeydown}
          next-icon={`${TComponents?.IconList?.common ?? 'fas dx-icon'} ${TComponents?.IconList?.arrowRight ?? 'icon-t-arrow-right'}`}
          prev-icon={`${TComponents?.IconList?.common ?? 'fas dx-icon'} ${TComponents?.IconList?.arrowLeft ?? 'icon-t-arrow-left'}`}
        >
          {Array.isArray(mappingProps.listDataSource) &&
          mappingProps.listDataSource.length > 0
            ? mappingProps.listDataSource.map((item, index) => (
                <CarouselSlide
                  name={index}
                  img-src={item[mappingProps.urlField]}
                  class={
                    item[mappingProps.urlField]
                      ? ''
                      : 'column no-wrap flex-center'
                  }
                >
                  <div class='text-center'>
                    {item[mappingProps.urlField] ? '' : mappingProps.noDataText}
                  </div>
                </CarouselSlide>
              ))
            : [{}, {}].map((item, index) => (
                <CarouselSlide
                  name={index}
                  class='column no-wrap flex-center'
                  style='padding:0'
                >
                  <span class='text-center'>{mappingProps.noDataText}</span>
                </CarouselSlide>
              ))}
        </Component>
      );
    };
  },
});
